package com.miya.demo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.miya.demo.common.exception.BusinessException;
import com.miya.demo.model.dto.system.MenuAddDTO;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.miya.demo.mapper.MenuMapper;
import com.miya.demo.entity.Menu;
import com.miya.demo.service.MenuService;

/**
 * 菜单服务impl
 *
 * @author Caixiaowei
 * @date 2022/08/18
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService{

    /**
     * 新增资源
     *
     * @param menuAddDTO 菜单dto
     */
    @Override
    public void add(MenuAddDTO menuAddDTO) {
        String menuName = menuAddDTO.getMenuName();
        String path = menuAddDTO.getPath();
        String perms = menuAddDTO.getPerms();
        List<Menu> list = this.lambdaQuery()
                .and(e -> {
                    e.eq(Menu::getMenuName, menuName)
                            .or()
                            .eq(Menu::getPath, path)
                            .or()
                            .eq(Menu::getPerms, perms);
                })
                .list();
        if (CollUtil.isNotEmpty(list)) {
            if (list.stream().anyMatch(e -> StrUtil.equals(menuName, e.getMenuName()))) {
                throw new BusinessException("资源名称已存在。");
            } else if (list.stream().anyMatch(e -> StrUtil.equals(path, e.getPath()))) {
                throw new BusinessException("资源路径已存在。");
            } else if (list.stream().anyMatch(e -> StrUtil.equals(perms, e.getPerms()))) {
                throw new BusinessException("资源标识已存在。");
            }
        }
        Menu menu = BeanUtil.copyProperties(menuAddDTO, Menu.class);
        this.save(menu);
    }
}
